import { defineStore } from 'pinia'
import { getInfoUser, loginOut } from '@/api/user'
import { ElMessage } from 'element-plus'
import { usePermissionStore } from '@/store/modules/permission'
import useCurrentRoleStore from '@/store/modules/current-role'

export const useUserStore = defineStore({
  // id: 必须的，在所有 Store 中唯一
  id: 'saasState',
  // state: 返回对象的函数
  state: () => ({
    // 登录token
    token: '',
    // 登录用户信息
    userInfo: {
      authorsCode: [],
      avatar: '',
      id: '',
      name: '',
      networkId: '',
      nickname: '',
      phone: '',
      userId: '',
    } as {
      authorsCode: Array<string>
      avatar: string
      id: string
      name: string
      networkId: string | null
      nickname: string
      phone: string
      userId: string
    },
    account: '',
    row: {
      tokenValue: '', //登录token
      expireIn: null, //过期时间
      tokenStartTime: null, //登录当前时间
      refreshToken: '', //刷新token
      tokenName: '',
    } as {
      tokenValue: string
      expireIn: null | number
      tokenStartTime: null | number
      refreshToken: string
      tokenName: string
    },
    // 角色
    roles: ['admin'],
    role: [] as AccountAPIResponse.AccountConnectEnterprise['customerRoleVos'], //角色账号列表
  }),
  getters: {
    isCurrentRoleNetwork: (state) => {
      if (!state.role) {
        return false
      }

      if (!state.role[0]) {
        return false
      }

      return state.role[0].roleType === 2
    },
  },
  // 可以同步 也可以异步
  actions: {
    // 登录
    async login_in() {
      //
    },
    getRoles() {
      return new Promise((resolve) => {
        resolve(this.roles)
      })
    },
    getInfo() {
      getInfoUser().then((res) => {
        this.userInfo = res.data.data
      })
    },
    // 退出
    logout() {
      return new Promise((resolve) => {
        loginOut().then((res) => {
          if (res.data.code == 20000) {
            const PermissionStore = usePermissionStore()
            const { clearCurrentRole } = useCurrentRoleStore()
            this.row = {
              tokenValue: '', //登录token
              expireIn: null, //过期时间
              tokenStartTime: null, //登录当前时间
              refreshToken: '', //刷新token
              tokenName: '',
            }
            this.token = ''
            this.roles = []
            PermissionStore.clearRoutes()
            clearCurrentRole()
            resolve(null)
          } else {
            ElMessage({
              message: res.data.message,
              type: 'warning',
            })
            return
          }
        })
      })
    },
  },
  // 进行持久化存储
  persist: {
    // 本地存储的名称
    key: 'saasState',
    //保存的位置
    storage: window.sessionStorage, //localstorage
  },
})
